package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.mes.produce.OrderStatusEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.MaterialReadyEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.OrderTypeEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.QRCodeRuleEnum;
import com.hunttown.mes.rpc.domain.enums.purchase.ProductTypeEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-03-30 15:28:37
 */
@Controller
@RequestMapping(value = "/mes/produce-order")
public class MesProduceOrderController {

    private final static Logger logger = LoggerFactory.getLogger(MesProduceOrderController.class);

    private final MesProduceOrderManageService mesProduceOrderService;
    private final MesProduceOrderSaleManageService orderSaleRelService;
    private final MesProducePassStationManageService mesProducePassStationService;
    private final MesProducePassStationDetailManageService mesProducePassStationDetailService;
    private final MesProducePackageManageService mesProducePackageService;
    private final MesProducePackageRuleManageService packageRuleService;
    private final MesProductManageService productService;
    private final MesOrderMaterialManageService orderMaterialService;
    private final MesSaleOrderManageService saleOrderService;
    private final MesSaleOrderDetailManageService saleOrderDetailService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final TransportPurchaseOutManageService purchaseOutService;
    private final TransactionService transactionService;
    private final WorkflowApplyManageService applyManageService;

    @Autowired
    public MesProduceOrderController(MesProduceOrderManageService mesProduceOrderService, MesProduceOrderSaleManageService orderSaleRelService, MesProducePassStationManageService mesProducePassStationService, MesProducePassStationDetailManageService mesProducePassStationDetailService, MesProducePackageManageService mesProducePackageService, MesProducePackageRuleManageService packageRuleService, MesProductManageService productService, MesOrderMaterialManageService orderMaterialService, MesSaleOrderManageService saleOrderService, MesSaleOrderDetailManageService saleOrderDetailService, AnalysisManageManageService manageService, ModelService modelService, TransportPurchaseManageService purchaseService, TransportPurchaseDetailManageService purchaseDetailService, TransportPurchaseOutManageService purchaseOutService, TransactionService transactionService, WorkflowApplyManageService applyManageService) {
        this.mesProduceOrderService = mesProduceOrderService;
        this.orderSaleRelService = orderSaleRelService;
        this.mesProducePassStationService = mesProducePassStationService;
        this.mesProducePassStationDetailService = mesProducePassStationDetailService;
        this.mesProducePackageService = mesProducePackageService;
        this.packageRuleService = packageRuleService;
        this.productService = productService;
        this.orderMaterialService = orderMaterialService;
        this.saleOrderService = saleOrderService;
        this.saleOrderDetailService = saleOrderDetailService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.purchaseService = purchaseService;
        this.purchaseDetailService = purchaseDetailService;
        this.purchaseOutService = purchaseOutService;
        this.transactionService = transactionService;
        this.applyManageService = applyManageService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, MesProduceOrderDTOQuery dtoQuery) {

        //初始化日期（90天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(90), DateConvertUtils.getPastDate(0)));
        }

        dtoQuery.setParentId(0);
        dtoQuery.setOrderBy("order by id desc");
        Page<MesProduceOrderDTO> dataPage = mesProduceOrderService.getForPage(dtoQuery);

        for (MesProduceOrderDTO item : dataPage.getItems()) {
            item.setMaterialReadyName(MaterialReadyEnum.getEnumByKey(item.getMaterialReady()));
            item.setStatusName(OrderStatusEnum.getEnumByKey(item.getStatus()));

            //获取拆单
            List<MesProduceOrderDTO> childList = mesProduceOrderService.getChildList(item.getId());
            for (MesProduceOrderDTO child : childList) {
                child.setMaterialReadyName(MaterialReadyEnum.getEnumByKey(child.getMaterialReady()));
                child.setStatusName(OrderStatusEnum.getEnumByKey(child.getStatus()));
            }
            item.setChildList(childList);
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //订单日期
        if (StringUtils.isNotBlank(dtoQuery.getDaterange())) {
            String[] date = dtoQuery.getDaterange().split("~");
            if (date.length == 2) {
                model.addAttribute("startDate", date[0].trim());
                model.addAttribute("endDate", date[1].trim());
            }
        }

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"S-D-SCDD-BJ", "S-D-SCDD-SC", "S-D-SCDD-QTY", "S-D-SCDD-QTJC", "S-D-SCDD-DB",
                "S-D-SCDD-DDGZ", "S-D-SCDD-KG", "S-D-SCDD-CD", "S-D-SCDD-WG"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/produce-order/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        MesProduceOrderDTO obj;

        if (id > 0) {
            obj = mesProduceOrderService.getById(id);

            //region 获取销售订单关联表
            MesProduceOrderSaleDTOQuery orderQuery = new MesProduceOrderSaleDTOQuery();
            orderQuery.setProduceId(id);
            orderQuery.setStopFlag(0);
            orderQuery.setPageSize(100);
            Page<MesProduceOrderSaleDTO> produceOrderPage = orderSaleRelService.getForPage(orderQuery);
            for (MesProduceOrderSaleDTO item : produceOrderPage.getItems()) {
                MesSaleOrderDTO sale = saleOrderService.getById(item.getSaleId());
                if (sale != null) {
                    item.setSaleName(sale.getOrderTitle());
                    item.setSaleNo(sale.getOrderNo());
                }

                MesSaleOrderDetailDTO detail = saleOrderDetailService.getById(item.getSaleDetailId());
                if (detail != null) {
                    item.setSaleDetailName(detail.getProductName());
                    item.setSpecialName(detail.getSpecialName());
                }
            }
            model.addAttribute("produceOrderList", produceOrderPage.getItems());
            //endregion

            //region 获取生产订单原料表
            MesOrderMaterialDTOQuery materiallQuery = new MesOrderMaterialDTOQuery();
            materiallQuery.setTableId(191);
            materiallQuery.setRecordId(id);
            materiallQuery.setPageSize(100);
            Page<MesOrderMaterialDTO> materialPage = orderMaterialService.getForPage(materiallQuery);
            for (MesOrderMaterialDTO item : materialPage.getItems()) {
                item.setGoodsTypeName(ProductTypeEnum.getEnumByKey(item.getGoodsType()));
            }
            model.addAttribute("partsDetailList", materialPage.getItems());
            //endregion

        } else {
            obj = new MesProduceOrderDTO();
            obj.setId(0);
            obj.setParentId(0);
            obj.setEstimateStartTime(new Date());
            obj.setEstimateEndTime(new Date());
            obj.setOperateTime(new Date());
            obj.setOrderType(2);
            obj.setEstimateCount(0);
            obj.setMaterialReady(0);
            obj.setStatus(0);

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            obj.setOperator(curr_obj.getId());

            obj.setOrderCode(GeneralUtils.GenTimeSeries(4, null, null));
        }
        model.addAttribute("Obj", obj);

        //生产类型
        model.addAttribute("orderTypeList", OrderTypeEnum.getEnumList());

        //二维码生成规则
        model.addAttribute("qrCodeRuleList", QRCodeRuleEnum.getEnumList());

        //是否备料
        model.addAttribute("materialReadyList", MaterialReadyEnum.getEnumList());

        //订单状态
        model.addAttribute("statusList", OrderStatusEnum.getEnumList());

        //下单人
        modelService.getManagerPage(model);

        //获取生产产品
        modelService.getMesProductPage(model);

        //生产工艺
        modelService.getMesWorkmanship(model);

        //生产线
        modelService.getMesProduceLine(model);

        return "mes/produce-order/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesProduceOrderDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        int orderid = 0; //新生成的订单ID
        int order_apply = 0; //新生成的审批ID

        try {
            //日期
            objDTO.setStartTime(DateConvertUtils.strToDate("1990-01-01"));
            objDTO.setEndTime(objDTO.getStartTime());
            objDTO.setEstimateStartTime(DateConvertUtils.strToDate(objDTO.getEstimateStartTimeSr()));
            objDTO.setEstimateEndTime(DateConvertUtils.strToDate(objDTO.getEstimateEndTimeSr()));
            objDTO.setOperateTime(DateConvertUtils.strToDate(objDTO.getOperateTimeSr()));

            //产品名称
            if (objDTO.getProductId() > 0) {
                MesProductDTO product = productService.getById(objDTO.getProductId());
                if (product != null) {
                    objDTO.setProductName(product.getProductName());
                    objDTO.setSpecialName(product.getSpecialName());
                }
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                MesProduceOrderDTOQuery query = new MesProduceOrderDTOQuery();
                query.setOrderCode(objDTO.getOrderCode());
                MesProduceOrderDTO obj = mesProduceOrderService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此生产订单已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getStatus() == null) {
                objDTO.setStatus(0);
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO.setRealCount(0);
                objDTO.setOutputCount(0);
                objDTO.setDamageCount(0);
                objDTO.setGoodRate(BigDecimal.ZERO);
                objDTO.setIsInStore(0);
                objDTO = mesProduceOrderService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                orderid = objDTO.getId(); //赋值

                //region 创建审批单
                Map<String, String> param = new HashMap<>();
                param.put("applyTitle", String.format("%s的（%s）审批", modelService.getManageName(objDTO.getOperator()), objDTO.getOrderName().replace("审批", "")));

                //[改版后]审批人走的是会员系统
                param.put("firstExector", modelService.getUserIdByAdminId(objDTO.getOperator()) + "");

                Integer applyId = transactionService.createApplyWithout("order_approve", "mes_produce_order", objDTO.getId(), objDTO.getAdminId(), param);
                if (applyId > 0) {
                    order_apply = applyId;

                    //更新生产订单表中的applyId
                    MesProduceOrderDTO updateDto = new MesProduceOrderDTO();
                    updateDto.setId(objDTO.getId());
                    updateDto.setApplyId(applyId);
                    mesProduceOrderService.updateInfoById(updateDto);

                } else {
                    //审批流程生成失败 删除已经生成的出库单
                    mesProduceOrderService.delete(objDTO.getId());

                    //程序终止，返回失败信息
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
                //endregion

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesProduceOrderService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region [01].生产-销售关联订单表.保存成功后更新
            String[] f_d_id = request.getParameterValues("f_d_id");
            String[] f_orderid = request.getParameterValues("f_orderid"); //sale_id
            String[] f_productid = request.getParameterValues("f_productid"); //sale_detail_id
            String[] f_ordercount = request.getParameterValues("f_ordercount");
            String[] f_producecount = request.getParameterValues("f_producecount");

            //1.获取已保存的销售明细
            MesProduceOrderSaleDTOQuery saleHistoryQuery = new MesProduceOrderSaleDTOQuery();
            saleHistoryQuery.setProduceId(objDTO.getId());
            saleHistoryQuery.setStopFlag(0);
            saleHistoryQuery.setPageSize(100);
            Page<MesProduceOrderSaleDTO> saleHistoryPage = orderSaleRelService.getForPage(saleHistoryQuery);

            //2. 保存到数据库
            if (f_d_id != null && f_d_id.length > 0) {

                List<Integer> newSaleOrderIds = new ArrayList<>(); //提交上来的，已保存过的ID
                MesProduceOrderSaleDTO insert;

                for (int i = 0; i < f_d_id.length; i++) {
                    int producecount = Integer.parseInt(f_producecount[i]);
                    if (producecount <= 0) {
                        continue;
                    }

                    insert = new MesProduceOrderSaleDTO();
                    insert.setProduceId(objDTO.getId());
                    insert.setSaleId(Integer.parseInt(f_orderid[i]));
                    insert.setSaleDetailId(Integer.parseInt(f_productid[i]));
                    insert.setOrderCount(Integer.parseInt(f_ordercount[i]));
                    insert.setProduceCount(producecount);
                    insert.setRealProduceCount(0);
                    insert.setAdminId(curr_obj.getId());
                    insert.setCreateTime(new Date());
                    insert.setStopFlag(0);
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_d_id[i]);
                    if (id > 0) {
                        //更新
                        newSaleOrderIds.add(id);
                        insert.setId(id);
                        orderSaleRelService.updateInfoById(insert);
                    } else {
                        //插入
                        orderSaleRelService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (MesProduceOrderSaleDTO item : saleHistoryPage.getItems()) {
                    if (!newSaleOrderIds.contains(item.getId())) {
                        orderSaleRelService.delete(item.getId());
                    }
                }
            }
            //endregion

            //region [02].订单用料明细表.保存成功后更新
            String[] f_id = request.getParameterValues("f_id");
            String[] f_partid = request.getParameterValues("f_partid");
            String[] f_count = request.getParameterValues("f_count");
            String[] f_countsingle = request.getParameterValues("f_countsingle");

            //1.获取已保存的原料明细
            MesOrderMaterialDTOQuery materiallHistoryQuery = new MesOrderMaterialDTOQuery();
            materiallHistoryQuery.setTableId(191);
            materiallHistoryQuery.setRecordId(objDTO.getId());
            materiallHistoryQuery.setPageSize(100);
            Page<MesOrderMaterialDTO> materialHistoryPage = orderMaterialService.getForPage(materiallHistoryQuery);

            //2. 保存到数据库
            if (f_id != null && f_id.length > 0) {

                List<Integer> newMaterailIds = new ArrayList<>(); //提交上来的，已保存过的ID
                MesOrderMaterialDTO insert;
                TransportPurchaseDTO partObj;

                for (int i = 0; i < f_id.length; i++) {
                    int count = Integer.parseInt(f_count[i]);
                    if (count <= 0) {
                        continue;
                    }

                    int partid = Integer.parseInt(f_partid[i]);
                    if (partid <= 0) {
                        continue;
                    }

                    partObj = purchaseService.getById(partid);
                    if (partObj == null) {
                        continue;
                    }

                    insert = new MesOrderMaterialDTO();
                    insert.setTableId(191);
                    insert.setRecordId(objDTO.getId());
                    insert.setPartId(partid);
                    insert.setMaterialName(partObj.getPartName());
                    insert.setMaterialNo(partObj.getPartNo());
                    insert.setCatalogId(partObj.getCatalogId());
                    insert.setGoodsType(partObj.getProductType());
                    insert.setSpecialName(partObj.getSpecialName());
                    insert.setSn(partObj.getSnCode());
                    insert.setUnit(partObj.getUnit());
                    insert.setCount(count);
                    insert.setCountSingle(Integer.parseInt(f_countsingle[i]));
                    insert.setCheckCount(0);
                    insert.setIsMaterialReady(0);
                    insert.setStorage(partObj.getStorage());
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_id[i]);
                    if (id > 0) {
                        //更新
                        newMaterailIds.add(id);
                        insert.setId(id);
                        orderMaterialService.updateInfoById(insert);
                    } else {
                        //插入
                        orderMaterialService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (MesOrderMaterialDTO item : materialHistoryPage.getItems()) {
                    if (!newMaterailIds.contains(item.getId())) {
                        orderMaterialService.delete(item.getId());
                    }
                }
            }
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            if (orderid > 0) {
                //删除已经生成的订单
                mesProduceOrderService.delete(orderid);

                //删除生产-销售关联明细
                MesProduceOrderSaleDTOQuery detailQuery = new MesProduceOrderSaleDTOQuery();
                detailQuery.setW_produceId(orderid);
                detailQuery.setDeleteFlag(1);
                orderSaleRelService.updateInfoByQuery(detailQuery);

                //删除订单用料明细
                MesOrderMaterialDTOQuery materailQuery = new MesOrderMaterialDTOQuery();
                materailQuery.setW_tableId(191);
                materailQuery.setRecordId(orderid);
                materailQuery.setDeleteFlag(1);
                orderMaterialService.updateInfoByQuery(materailQuery);

                //删除审批单
                applyManageService.delete(order_apply);
            }

            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesProduceOrderService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesProduceOrderService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesProduceOrderDTO obj = new MesProduceOrderDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesProduceOrderService.getById(id);
        }
        model = mesProduceOrderService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 生产订单齐套检查

    /**
     * 生产订单齐套检查
     *
     * @param model model
     * @param id    生产订单ID
     * @return vm
     */
    @RequestMapping(value = "/produceCompleteCheck", method = RequestMethod.POST)
    public String produceCompleteCheck(Model model, Integer id) {
        if (id == null || id <= 0) {
            return "mes/produce-order/produce-completecheck-modal";
        }

        MesProduceOrderDTO obj = mesProduceOrderService.getById(id);
        if (obj == null) {
            return "mes/produce-order/produce-completecheck-modal";
        }
        model.addAttribute("orderObj", obj);

        //A、是否已经锁定过库存
        int isAlreadyLock = 0;

        TransportPurchaseOutDTOQuery outQuery = new TransportPurchaseOutDTOQuery();
        outQuery.setTableId(191);
        outQuery.setRecordId(id);
        outQuery.setStopFlag(0);
        TransportPurchaseOutDTO out = purchaseOutService.getByQuery(outQuery);

        //B、是否已出过库
        int isOutStock = 0;

        if (out != null) {
            isAlreadyLock = 1;

            //如已经有过出库记录，则不能再次锁定
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(205);
            detailQuery.setRecordId(out.getId());
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);
            for (TransportPurchaseDetailDTO item : detailPage.getItems()) {
                if (item.getcCountReal() > 0) {
                    isOutStock = 1;
                    break;
                }
            }
        }

        //1.先取出当前生产订单所需要的物料
        MesOrderMaterialDTOQuery materiallQuery = new MesOrderMaterialDTOQuery();
        materiallQuery.setTableId(191);
        materiallQuery.setRecordId(id);
        materiallQuery.setPageSize(100);
        Page<MesOrderMaterialDTO> materialPage = orderMaterialService.getForPage(materiallQuery);

        int isCanLockStock = 1; //是否可以锁定库存

        //2.单独计算每个物料的库存
        List<Map<String, String>> rmapList;
        for (MesOrderMaterialDTO item : materialPage.getItems()) {
            item.setGoodsTypeName(ProductTypeEnum.getEnumByKey(item.getGoodsType()));

            //计算库存
            rmapList = purchaseDetailService.selectSumCount(item.getPartId());
            if (rmapList != null) {
                Map<String, String> rmap = rmapList.get(0);
                Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));
                item.setStockCount(r_counts - c_counts - s_counts);

                //判断是否可以锁定库存
                if (item.getCount() > item.getStockCount()) {
                    isCanLockStock = 0;
                }
            }
        }
        model.addAttribute("partsDetailList", materialPage.getItems());

        model.addAttribute("isCanLockStock", isCanLockStock);
        model.addAttribute("isAlreadyLock", isAlreadyLock);
        model.addAttribute("isOutStock", isOutStock);

        return "mes/produce-order/produce-completecheck-modal";
    }
    //endregion

    //region 齐套检查，锁定库存

    /**
     * 齐套检查，锁定库存
     *
     * @param orderId 生产订单ID
     * @param opType  1锁定、2重新锁定、3解锁库存
     * @return map
     */
    @RequestMapping(value = "/lockPurchaseStock", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> lockPurchaseStock(HttpServletRequest request, Integer orderId, Integer opType) {
        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);
        map.put("returnMessage", "库存操作失败！");

        //只有三种操作类型
        if (opType != 1 && opType != 2 && opType != 3) {
            return map;
        }

        if (orderId == null || orderId <= 0) {
            return map;
        }

        MesProduceOrderDTO obj = mesProduceOrderService.getById(orderId);
        if (obj == null) {
            return map;
        }

        //region A、获取已锁定的出库单
        TransportPurchaseOutDTO out = null;
        TransportPurchaseOutDTOQuery outQuery = new TransportPurchaseOutDTOQuery();
        outQuery.setTableId(191);
        outQuery.setRecordId(orderId);
        outQuery.setStopFlag(0);
        out = purchaseOutService.getByQuery(outQuery);

        //【optype=3】解锁库存
        if (opType == 3 && out != null) {
            purchaseOutService.delete(out.getId());
        }
        //endregion

        //region B、获取出库明细
        int isOutStock = 0;

        if (out != null) {

            //【optype=3】解锁库存
            if (opType == 3) {
                TransportPurchaseDetailDTOQuery updateQuery = new TransportPurchaseDetailDTOQuery();
                updateQuery.setW_tableId(205);
                updateQuery.setW_recordId(out.getId());
                updateQuery.setDeleteFlag(1);
                boolean isNext = purchaseDetailService.updateInfoByQuery(updateQuery);

                map.put("returnMessage", isNext ? "库存解锁成功！" : "库存解锁失败！");
                return map;
            }

            //出库明细
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(205);
            detailQuery.setRecordId(out.getId());
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);

            for (TransportPurchaseDetailDTO item : detailPage.getItems()) {
                if (item.getcCountReal() > 0) {
                    isOutStock = 1;
                    break;
                }
            }
        }
        //endregion

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        Date default_date = DateConvertUtils.strToDate("1990-01-01");

        //region 1.生成出库单，但不走审批流程，取物料时再生成出库单
        TransportPurchaseOutDTO outDTO = new TransportPurchaseOutDTO();
        outDTO.setId(0);
        outDTO.setParentId(0);
        outDTO.setTableId(191);
        outDTO.setRecordId(orderId);
        outDTO.setPurchaseType(2);
        outDTO.setOutType(1);
        outDTO.setOutName("生产（" + obj.getOrderName() + "）出库单");
        outDTO.setProId(0);
        outDTO.setOutNo(GeneralUtils.GenTimeSeries(4, null, null));
        outDTO.setReceiver(0);
        outDTO.setReceiveDate(new Date());
        outDTO.setCarId(0);
        outDTO.setDriverId(0);
        outDTO.setStatus(1);
        outDTO.setOperator(curr_obj.getId());
        outDTO.setOperateDate(new Date());
        outDTO.setReviewer(0);
        outDTO.setReviewDate(default_date);
        outDTO.setReviewStatus(0);
        outDTO.setRemark("生产订单锁定库存");
        outDTO.setApplyId(0);
        outDTO.setRelationId(0);
        outDTO.setAdminId(curr_obj.getId());
        outDTO.setCreateTime(new Date());
        outDTO.setStopFlag(0);
        outDTO.setDeleteFlag(0);

        //插入（锁定）
        if (opType == 1 && out == null) {
            outDTO = purchaseOutService.insert(outDTO);
        }

        //更新（重新锁定）
        if (opType == 2 && out != null && isOutStock == 0) {
            outDTO.setId(out.getId());
            purchaseOutService.updateInfoById(outDTO);

            //把明细删除，下面直接插入
            TransportPurchaseDetailDTOQuery updateQuery = new TransportPurchaseDetailDTOQuery();
            updateQuery.setW_tableId(205);
            updateQuery.setW_recordId(out.getId());
            updateQuery.setDeleteFlag(1);
            purchaseDetailService.updateInfoByQuery(updateQuery);
        }
        //endregion

        //region 2.生成出库明细
        if (outDTO.getId() > 0) {
            //2.生成出库明细
            //2.1 取出物料明细
            MesOrderMaterialDTOQuery materiallQuery = new MesOrderMaterialDTOQuery();
            materiallQuery.setTableId(191);
            materiallQuery.setRecordId(orderId);
            materiallQuery.setPageSize(100);
            Page<MesOrderMaterialDTO> materialPage = orderMaterialService.getForPage(materiallQuery);

            //2.2 插入明细表
            TransportPurchaseDetailDTO insert;
            for (MesOrderMaterialDTO item : materialPage.getItems()) {
                insert = new TransportPurchaseDetailDTO();
                insert.setParentId(0);
                insert.setTableId(205);
                insert.setRecordId(outDTO.getId());
                insert.setPurchaseType(outDTO.getPurchaseType());
                insert.setPartId(item.getPartId());
                insert.setProId(0);
                insert.setPurId(outDTO.getId());
                insert.setOpType(outDTO.getOutType() == 4 ? 3 : 2); //outtype=4是报废，其它是出库
                insert.setrPurchaseType(0);
                insert.setrPurchaser(0);
                insert.setrCompanyId(0);
                insert.setrPayCompanyId(0);
                insert.setrPayWay(0);
                insert.setrPrice(BigDecimal.ZERO);
                insert.setrCount(0);
                insert.setrInCount(0);
                insert.setrAmount(BigDecimal.ZERO);
                insert.setrTaxRate(BigDecimal.ZERO);
                insert.setrTax(BigDecimal.ZERO);
                insert.setrStoreCount(0);
                insert.setrPurchaseDate(default_date);
                insert.setrInDate(default_date);
                insert.setrSalePrice(BigDecimal.ZERO);
                insert.setrMarketPrice(BigDecimal.ZERO);
                insert.setrStorePrice(BigDecimal.ZERO);
                insert.setcOutType(outDTO.getOutType());
                insert.setcNoOrder(0);
                insert.setcStoreCount(0);
                insert.setcCountAll(item.getCount());
                insert.setcCount(item.getCount());
                insert.setcCountReal(0);
                insert.setcCountReturn(0);
                insert.setcCountNouse(0);
                insert.setcRepairId(0);
                insert.setcCarId(0);
                insert.setcDriverId(0);
                insert.setcUserId(0);
                insert.setcOutDate(default_date);
                insert.setsCount(0);
                insert.setsAdminId(0);
                insert.setsDate(default_date);
                insert.setReviewer(0);
                insert.setReviewDate(default_date);
                insert.setReviewStatus(0);
                insert.setStatus(0);
                insert.setBxId(0);
                insert.setApplyId(0);
                insert.setRelationId(0);
                insert.setAdminId(curr_obj.getId());
                insert.setCreateTime(new Date());
                insert.setStopFlag(0);
                insert.setDeleteFlag(0);

                //插入（锁定）
                if (opType == 1 && out == null) {
                    purchaseDetailService.insert(insert);
                }

                //更新（重新锁定，采用粗暴方式，删除后重新插入）
                if (opType == 2 && out != null && isOutStock == 0) {
                    purchaseDetailService.insert(insert);
                }
            }
        }
        //endregion

        //region 3.1锁定（更新为 已备料）、2重新锁定、3解锁库存（更新为 未备料）
        if (opType == 1) {
            MesProduceOrderDTO update = new MesProduceOrderDTO();
            update.setId(orderId);
            update.setMaterialReady(1);
            update.setStatus(10);
            mesProduceOrderService.updateInfoById(update);
        }

        if (opType == 3) {
            MesProduceOrderDTO update = new MesProduceOrderDTO();
            update.setId(orderId);
            update.setMaterialReady(0);
            update.setStatus(5);
            mesProduceOrderService.updateInfoById(update);
        }
        //endregion

        map.put("returnCode", 1);
        map.put("returnMessage", "库存锁定成功！");
        return map;
    }
    //endregion

    //region 拆单

    /**
     * 编辑
     *
     * @param model     model模型
     * @param produceId 生产订单id
     * @return model
     */
    @RequestMapping(value = "/unpackOrder", method = RequestMethod.GET)
    public String unpackOrder(HttpServletRequest request, Model model, Integer produceId) {
        if (produceId == null || produceId <= 0) {
            throw new RuntimeException("未查询到主订单信息");
        }

        MesProduceOrderDTO obj = mesProduceOrderService.getById(produceId);
        if (obj == null) {
            throw new RuntimeException("未查询到主订单信息");
        }
        model.addAttribute("mainOrderName", obj.getOrderName());

        obj.setOrderName(obj.getOrderName() + "-拆单");
        obj.setOrderCode(obj.getOrderCode() + "-1");

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        obj.setOperator(curr_obj.getId()); //拆单人
        obj.setOperateTime(new Date());    //拆单日期

        model.addAttribute("Obj", obj);

        //生产类型
        model.addAttribute("orderTypeList", OrderTypeEnum.getEnumList());

        //二维码生成规则
        model.addAttribute("qrCodeRuleList", QRCodeRuleEnum.getEnumList());

        //是否备料
        model.addAttribute("materialReadyList", MaterialReadyEnum.getEnumList());

        //订单状态
        model.addAttribute("statusList", OrderStatusEnum.getEnumList());

        //下单人
        modelService.getManagerPage(model);

        //获取生产产品
        modelService.getMesProductPage(model);

        //生产工艺
        modelService.getMesWorkmanship(model);

        //生产线
        modelService.getMesProduceLine(model);

        //获取包信息
        MesProducePackageDTOQuery packageQuery = new MesProducePackageDTOQuery();
        packageQuery.setProduceId(produceId);
        packageQuery.setStopFlag(0);
        Page<MesProducePackageDTO> packagePage = mesProducePackageService.getForPage(packageQuery);
        model.addAttribute("packageList", packagePage.getItems());

        return "mes/produce-order/unpack-order";
    }

    //执行拆单操作
    @RequestMapping(value = "/doUnpackOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doUnpackOrder(HttpServletRequest request, Integer parentId, String orderName, String orderCode, Integer estimateCount, Integer operator, String operateTimeSr, String remark, String unpackageIds) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        //做一些验证
        if (estimateCount <= 0 || StringUtils.isBlank(unpackageIds)) {
            map.put("returnMessage", "缺少参数");
            return map;
        }

        //获取主单信息
        MesProduceOrderDTO obj = mesProduceOrderService.getById(parentId);
        if (obj == null) {
            map.put("returnMessage", "未查询到放单信息");
            return map;
        }

        //[1-1].修改主单部分信息，然后插入子单
        obj.setId(0);
        obj.setParentId(parentId);
        obj.setOrderName(orderName);
        obj.setOrderCode(orderCode);
        obj.setEstimateCount(estimateCount);
        obj.setOperator(operator);
        obj.setOperateTime(DateConvertUtils.strToDate(operateTimeSr));
        obj.setRemark(remark);

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        obj.setAdminId(curr_obj.getId());
        obj.setCreateTime(new Date());
        obj = mesProduceOrderService.insert(obj);

        if (obj == null || obj.getId() <= 0) {
            map.put("returnMessage", "拆单失败");
            return map;
        }

        //[1-2].复制一条生产明细，并插入
        MesProduceOrderSaleDTO relObj = orderSaleRelService.getByProduceId(parentId);
        if (relObj != null) {
            relObj.setId(0);
            relObj.setProduceId(obj.getId());
            relObj.setOrderCount(estimateCount);
            relObj.setProduceCount(estimateCount);
            relObj.setAdminId(curr_obj.getId());
            relObj.setCreateTime(new Date());
            orderSaleRelService.insert(relObj);
        }

        //[2-1].拆分包
        int start_number = 0;
        int end_number = 0;
        int i = 0;

        List<Integer> pkgIds = FormatUtils.commaToList_Integer(unpackageIds);

        for (Integer pkg : pkgIds) {
            i++;

            MesProducePackageDTO update = new MesProducePackageDTO();
            update.setId(pkg);
            update.setProduceId(obj.getId());
            mesProducePackageService.updateInfoById(update);

            //获取一些基本信息
            MesProducePackageDTO dto = mesProducePackageService.getById(pkg);
            if (dto != null) {
                if (i == 1) {
                    start_number = dto.getStartNumber();
                }

                if (i == pkgIds.size()) {
                    end_number = dto.getEndNumber();
                }
            }
        }

        //[2-2].复制拆包规则
        MesProducePackageRuleDTO ruleObj = packageRuleService.getByProduceId(parentId);
        if (ruleObj == null) {
            //删除刚生成的订单
            mesProduceOrderService.delete(obj.getId());

            map.put("returnMessage", "未查询到拆包规则，拆单失败");
            return map;
        }

        ruleObj.setId(0);
        ruleObj.setProduceId(obj.getId());
        ruleObj.setTotalCount(estimateCount);
        ruleObj.setPackageCount(pkgIds.size());
        ruleObj.setStartNumber(start_number);
        ruleObj.setEndNumber(end_number);
        ruleObj.setCreateTime(new Date());
        packageRuleService.insert(ruleObj);

        //[2-3].复制已过站环节
        MesProducePassStationDTOQuery passProcessQuery = new MesProducePassStationDTOQuery();
        passProcessQuery.setProduceId(parentId);
        passProcessQuery.setPassStatus(1);
        passProcessQuery.setStopFlag(0);
        Page<MesProducePassStationDTO> passProcessPage = mesProducePassStationService.getForPage(passProcessQuery);

        for (MesProducePassStationDTO item : passProcessPage.getItems()) {
            item.setId(0);
            item.setProduceId(obj.getId());
            item.setCreateTime(new Date());
            mesProducePassStationService.insert(item);
        }

        //[3].更新已过站明细
        for (Integer pkg : pkgIds) {
            MesProducePassStationDetailDTOQuery query = new MesProducePassStationDetailDTOQuery();
            query.setProduceId(obj.getId());
            query.setW_packageId(pkg);
            mesProducePassStationDetailService.updateInfoByQuery(query);
        }

        map.put("returnCode", 1);
        map.put("returnMessage", "拆单成功");
        return map;
    }
    //endregion

    //region 启动订单（开工）
    @RequestMapping(value = "/startOperation", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> startOperation(HttpServletRequest request, Integer produceId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (produceId == null || produceId <= 0) {
            map.put("returnMessage", "未查询到订单信息");
            return map;
        }

        //更新生产订单状态和时间
        MesProduceOrderDTO update = new MesProduceOrderDTO();
        update.setId(produceId);
        update.setStatus(12);
        update.setStartTime(new Date());
        boolean isNext = mesProduceOrderService.updateInfoById(update);

        //更新销售订单状态
        if (isNext) {
            //1、生产订单、销售订单关联表取出数据
            MesProduceOrderSaleDTOQuery orderQuery = new MesProduceOrderSaleDTOQuery();
            orderQuery.setProduceId(produceId);
            orderQuery.setStopFlag(0);
            orderQuery.setPageSize(100);
            Page<MesProduceOrderSaleDTO> produceOrderPage = orderSaleRelService.getForPage(orderQuery);
            for (MesProduceOrderSaleDTO item : produceOrderPage.getItems()) {
                //2、更新
                MesSaleOrderDTO upinfo = new MesSaleOrderDTO();
                upinfo.setId(item.getSaleId());
                upinfo.setStatus(12);
                saleOrderService.updateInfoById(upinfo);
            }
        }

        if (isNext) {
            map.put("returnCode", 1);
            map.put("returnMessage", "订单启动成功！");
        } else {
            map.put("returnMessage", "订单启动失败！");
        }

        return map;
    }
    //endregion

    //region 结束订单（完工）
    @RequestMapping(value = "/completeProduceOrder", method = RequestMethod.GET)
    public String completeProduceOrder(Model model, Integer produceId) {

        //region 获取生产订单信息
        MesProduceOrderDTO produceObj = mesProduceOrderService.getById(produceId);
        if (produceObj == null) {
            throw new RuntimeException("未查询到生产订单信息");
        }
        produceObj.setShipName(modelService.getMesShipName(produceObj.getShipId()));
        produceObj.setProduceLineName(modelService.getMesProduceLineName(produceObj.getProduceLine()));
        produceObj.setMaterialReadyName(MaterialReadyEnum.getEnumByKey(produceObj.getMaterialReady()));
        produceObj.setOperatorCn(modelService.getManageName(produceObj.getOperator()));
        produceObj.setStatusName(OrderStatusEnum.getEnumByKey(produceObj.getStatus()));
        produceObj.setOrderTypeName(OrderTypeEnum.getEnumByKey(produceObj.getOrderType()));
        produceObj.setSnRuleName(QRCodeRuleEnum.getEnumByKey(produceObj.getSnRule()));
        model.addAttribute("produceObj", produceObj);
        //endregion

        //region 计算总数，良品，良品率
        //入场总数 a：第一道工序的总数（方式二：b+c）
        //良品数   b：最后一道工序的良品数
        //不良品   c：a-b（方式二：有不良品的累计和）
        //良品率   d：b/a

        //[1].获取最后一条过站信息（换一种方式，因为第一道工序无法确定数量）
        //MesProducePassStationDTO firstPassStationObj = mesProducePassStationService.getFirstByProduceId(produceId);
        //int total_count = firstPassStationObj.getTotalCount();

        //[1].不良品，方式二：取出所有过站中不良品
        MesProducePassStationDTOQuery passProcessQuery = new MesProducePassStationDTOQuery();
        passProcessQuery.setProduceId(produceId);
        passProcessQuery.setStopFlag(0);
        Page<MesProducePassStationDTO> passProcessPage = mesProducePassStationService.getForPage(passProcessQuery);

        int bad_count = 0;
        for (MesProducePassStationDTO item : passProcessPage.getItems()) {
            bad_count += item.getBadCount();
        }

        //[2].良品，获取最后一条过站信息
        MesProducePassStationDTO lastPassStationObj = mesProducePassStationService.getByProduceId(produceId);
        int good_count = lastPassStationObj.getGoodCount();

        //[3].入场总数
        int total_count = good_count + bad_count;

        //[4].良品率
        float good_rate = (float) good_count / (float) total_count;
        String s_good_rate = FormatUtils.fmtNPoint(good_rate, 4);

        model.addAttribute("totalCount", total_count);
        model.addAttribute("goodCount", good_count);
        model.addAttribute("badCount", bad_count);
        model.addAttribute("goodRate", s_good_rate);

        //endregion

        //region 获取销售订单关联表
        MesProduceOrderSaleDTOQuery orderQuery = new MesProduceOrderSaleDTOQuery();
        orderQuery.setProduceId(produceId);
        orderQuery.setStopFlag(0);
        orderQuery.setPageSize(100);
        Page<MesProduceOrderSaleDTO> produceOrderPage = orderSaleRelService.getForPage(orderQuery);

        int plan_produce_count = 0; //本次一共要生产多少产品
        for (MesProduceOrderSaleDTO item : produceOrderPage.getItems()) {
            MesSaleOrderDTO sale = saleOrderService.getById(item.getSaleId());
            if (sale != null) {
                item.setSaleName(sale.getOrderTitle());
                item.setSaleNo(sale.getOrderNo());
            }

            MesSaleOrderDetailDTO detail = saleOrderDetailService.getById(item.getSaleDetailId());
            if (detail != null) {
                item.setSaleDetailName(detail.getProductName());
                item.setSpecialName(detail.getSpecialName());
            }

            plan_produce_count += item.getProduceCount();
        }

        //实际生产数，做加权平均
        int allocation_count = 0; //本次已经累计分配了多少

        for (int i = 0; i < produceOrderPage.getItems().size(); i++) {
            MesProduceOrderSaleDTO dto = produceOrderPage.getItems().get(i);

            if (i == produceOrderPage.getItems().size() - 1) { //最后一条
                int rc = good_count - allocation_count;
                dto.setRealProduceCount(rc);
            } else {
                int rc = Math.round(((float) dto.getProduceCount() / (float) plan_produce_count) * good_count);
                dto.setRealProduceCount(rc);

                allocation_count += rc;
            }
        }

        model.addAttribute("produceOrderSaleList", produceOrderPage.getItems());
        //endregion

        return "mes/produce-order/complete-order";
    }

    /**
     * 执行订单完工
     *
     * @param request    req
     * @param produceId  生产订单ID
     * @param totalCount 总生产数
     * @param goodCount  良品
     * @param badCount   不良品
     * @param goodRate   良品率
     * @return map
     */
    @RequestMapping(value = "/doCompleteProduceOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doCompleteProduceOrder(HttpServletRequest request, Integer produceId,
                                                      Integer totalCount, Integer goodCount, Integer badCount, float goodRate) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (produceId == null || produceId <= 0) {
            map.put("returnMessage", "未查询到生产订单信息");
            return map;
        }

        MesProduceOrderDTO produceObj = mesProduceOrderService.getById(produceId);
        if (produceObj == null) {
            throw new RuntimeException("未查询到生产订单信息");
        }

        //1、更新生产订单信息
        MesProduceOrderDTO update = new MesProduceOrderDTO();
        update.setId(produceId);
        update.setStatus(20);
        update.setEndTime(new Date());
        update.setOutputCount(goodCount); //产出数量，良品
        update.setDamageCount(badCount); //不良品
        update.setGoodRate(new BigDecimal(goodRate)); //良品率
        boolean isNext = mesProduceOrderService.updateInfoById(update);
        if (!isNext) {
            map.put("returnMessage", "生产订单更新失败！");
            return map;
        }

        //2、更新生产订单-销售订单关联表信息
        String[] f_id = request.getParameterValues("f_id");
        String[] f_realproducecount = request.getParameterValues("f_realproducecount");

        if (f_id != null && f_id.length > 0) {
            for (int i = 0; i < f_id.length; i++) {
                int id = Integer.parseInt(f_id[i]);
                int real_count = Integer.parseInt(f_realproducecount[i]);

                if (id <= 0) {
                    continue;
                }

                //先获取一下，里面有有用信息
                MesProduceOrderSaleDTO dto = orderSaleRelService.getById(id);

                //2-1、更新生产订单-销售订单关联表（子单在拆单的时候会插入一条，这里可以更新）
                MesProduceOrderSaleDTO updateinfo = new MesProduceOrderSaleDTO();
                updateinfo.setId(id);
                updateinfo.setRealProduceCount(real_count);
                orderSaleRelService.updateInfoById(updateinfo);

                //子单不更新销售订单信息，同时插入一条子销售明细
                if (produceObj.getParentId() == 0) {

                    //region 处理主单情况
                    //2-2、更新销售订单信息
                    MesSaleOrderDTO saleUpdate = new MesSaleOrderDTO();
                    saleUpdate.setId(dto.getSaleId());
                    saleUpdate.setStatus(20); //这里会出现一种情况，就是一个订单分多次生产，目前暂不考虑
                    saleOrderService.updateInfoById(saleUpdate);

                    //2-3、更新销售订单明细（这里注意，一定要累加，不能覆盖，原因同上，一个订单可能分多次生产）
                    MesSaleOrderDetailDTO origin = saleOrderDetailService.getById(dto.getSaleDetailId());
                    if (origin != null) {
                        MesSaleOrderDetailDTO saleDetailUpdate = new MesSaleOrderDetailDTO();
                        saleDetailUpdate.setId(dto.getSaleDetailId());
                        saleDetailUpdate.setRealProduceCount(origin.getRealProduceCount() + real_count);
                        saleOrderDetailService.updateInfoById(saleDetailUpdate);
                    }
                    //endregion

                } else {

                    //region 处理子单情况
                    //获取一条明细信息用来复制
                    MesSaleOrderDetailDTO origin = saleOrderDetailService.getByOrderId(dto.getSaleId());
                    if (origin == null) {
                        continue;
                    }

                    String pin = AdminBaseClass.getPin(request);
                    AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

                    //插入一条子销售明细
                    origin.setId(0);
                    origin.setOrderType(1);
                    origin.setOrderCount(totalCount);
                    origin.setStoreCount(0);
                    origin.setProduceCount(0);
                    origin.setRealProduceCount(goodCount);
                    origin.setAdminId(curr_obj.getId());
                    origin.setCreateTime(new Date());
                    saleOrderDetailService.insert(origin);
                    //endregion

                }
            }
        }

        map.put("returnCode", 1);
        map.put("returnMessage", "生产订单更新成功！");
        return map;
    }
    //endregion
}